package com.purchase.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.purchase.entity.Coupon;
import com.purchase.entity.WxUser;
import com.purchase.mapper.*;
import com.purchase.service.CouponService;
import com.purchase.util.LogInfo;
import com.purchase.util.RequestForm;
import com.purchase.util.ResponseForm;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class CouponServiceImpl implements CouponService {

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private WxUserMapper wuMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private StoreActivityMapper storeActivityMapper;

    @Override
    public ResponseForm listForManage(RequestForm param) {
        ResponseForm result = new ResponseForm();
        Map<String, Object> paramMap = (Map<String, Object>) param.getData();
        try {
            com.purchase.util.Page.parsePage(paramMap);
            Page<Object> pageHelper = PageHelper.startPage((int) paramMap.get("page"), (int) paramMap.get("size"));
            List<Coupon> couponList = couponMapper.getCouponList(paramMap);
            result.setData(couponList);
            result.setTotal((int) pageHelper.getTotal());
        } catch (Exception e) {
            result.setStatus(false);
            result.setMessage(LogInfo.ERROR);
            log.error("查询后台优惠券列表error", e);
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseForm create(RequestForm param) {
        ResponseForm result = new ResponseForm();
        Map<String, Object> paramMap = (Map<String, Object>) param.getData();
        try {
            String name = (String) paramMap.get("name");
            String type = (String) paramMap.get("type");
            String status = (String) paramMap.get("status");
            String startTime = (String) paramMap.get("startTime");
            String endTime = (String) paramMap.get("endTime");
            String couponAmount = (String) paramMap.get("couponAmount");
            String sillAmount = (String) paramMap.get("sillAmount");
            String activityIds = (String) paramMap.get("activityIds");
            String detail = (String) paramMap.get("detail");
            String discount = (String) paramMap.get("discount");
            String memberFlag = (String) paramMap.get("memberFlag");
            String isAllActivity = (String) paramMap.get("isAllActivity");
            String isNewUser = (String) paramMap.get("isNewUser");
            if (!StringUtils.isNotBlank(name) || !StringUtils.isNotBlank(type) || !StringUtils.isNotBlank(status)
                    || !StringUtils.isNotBlank(startTime) || !StringUtils.isNotBlank(endTime)) {
                result.setStatus(false);
                result.setMessage(LogInfo.PARAM_ERROR);
                log.error(LogInfo.PARAM_ERROR);
                return result;
            }
            List<String> idList = null;
            if (activityIds != null && !"".equals(activityIds)) {
                idList = Arrays.asList(activityIds.split(","));
            }
            if (isAllActivity != null && "1".equals(isAllActivity)) {
                //如果关联全部活动
                idList = storeActivityMapper.getAllActivityIds();
            }


            Coupon coupon = new Coupon();
            coupon.setName(name);
            coupon.setType(Integer.valueOf(type));
            coupon.setStatus(Integer.valueOf(status));
            coupon.setStartTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startTime));
            coupon.setEndTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endTime));
            coupon.setCouponAmount(couponAmount == null ? null : Integer.valueOf(couponAmount));
            coupon.setSillAmount(sillAmount == null ? null : Integer.valueOf(sillAmount));
            coupon.setDetail(detail);
            coupon.setDiscount(discount == null ? null : Integer.valueOf(discount));
            coupon.setMemberFlag(memberFlag == null ? null : Integer.valueOf(memberFlag));
            coupon.setIsAllActivity(isAllActivity == null ? null : Integer.valueOf(isAllActivity));
            coupon.setIsNewUser(isNewUser == null ? null : Integer.valueOf(isNewUser));
            couponMapper.createCoupon(coupon);
            if (idList != null) {
                //添加活动关联
                List<Map<String, Object>> mapList = new ArrayList<>();
                for (String activityId : idList) {
                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("activityId", Integer.valueOf(activityId));
                    hashMap.put("couponId", coupon.getId());
                    mapList.add(hashMap);
                }
                couponMapper.createCouponActivity(mapList);
            }

            //给老用户绑定新人专属优惠券
            if ("1".equals(isNewUser)) {
                this.bindNewUserCouponsToOldUsers(coupon.getId());
            }
        } catch (Exception e) {
            result.setStatus(false);
            result.setMessage(LogInfo.ERROR);
            log.error("创建优惠券error", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseForm modify(RequestForm param) {
        ResponseForm result = new ResponseForm();
        Map<String, Object> paramMap = (Map<String, Object>) param.getData();

        //活动ID
        String activityIds = (String) paramMap.get("activityIds");
        //是否关联全部活动
        String isAllActivity = (String) paramMap.get("isAllActivity");
        try {
            couponMapper.updateCoupon(paramMap);

            List<String> idList = null;
            if (activityIds != null && !"".equals(activityIds)) {
                idList = Arrays.asList(activityIds.split(","));
            }
            if (isAllActivity != null && "1".equals(isAllActivity)) {
                //如果关联全部活动
                idList = storeActivityMapper.getAllActivityIds();
            }

            if (idList != null) {
                //删除原活动关联
                couponMapper.delCouponActivity(paramMap);
                //添加活动关联
                List<Map<String, Object>> mapList = new ArrayList<>();
                for (String activityId : idList) {
                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("activityId", Integer.valueOf(activityId));
                    hashMap.put("couponId", paramMap.get("id"));
                    mapList.add(hashMap);
                }
                couponMapper.createCouponActivity(mapList);
            }
        } catch (Exception e) {
            result.setStatus(false);
            result.setMessage(LogInfo.ERROR);
            log.error("修改优惠券error", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    @Override
    public ResponseForm receive(RequestForm param) {
        ResponseForm result = new ResponseForm();
        Map<String, Object> paramMap = (Map<String, Object>) param.getData();
        try {
            String couponIds = (String) paramMap.get("couponIds");
            String wxUid = (String) paramMap.get("wxUid");
            if (!StringUtils.isNotBlank(couponIds) || !StringUtils.isNotBlank(wxUid)) {
                result.setStatus(false);
                result.setMessage(LogInfo.PARAM_ERROR);
                log.error(LogInfo.PARAM_ERROR);
                return result;
            }
            String[] ids = couponIds.split(",");
            //前台该活动该用户可见所有优惠券idList
            List<Integer> idList = new ArrayList<>();
            for (String id : ids) {
                idList.add(Integer.parseInt(id));
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("wxUid", wxUid);
//            //已领取的优惠券receivableIdList（不包含已用于支付的优惠券）
//            List<Integer> receivedIdList = couponMapper.getReceivedIdListV1(map);
            //已领取的优惠券receivableIdList（包含已用于支付的优惠券）
            List<Integer> receivedIdList = couponMapper.getReceivedIdListV2(map);
            //取差集即可领取的优惠券
            idList.removeAll(receivedIdList);
            if (idList.size() > 0) {
                List<Map<String, Object>> receivableIdList = new ArrayList<>();
                for (Integer id : idList) {
                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("wxUid", wxUid);
                    hashMap.put("couponId", id);
                    receivableIdList.add(hashMap);
                }
                //可领取的优惠券入库
                couponMapper.createCouponUser(receivableIdList);
            }
            result.setData(idList);
        } catch (Exception e) {
            result.setStatus(false);
            result.setMessage(LogInfo.ERROR);
            log.error("领取优惠券error", e);
        }
        return result;
    }

    @Override
    public ResponseForm receiveList(RequestForm param) {
        ResponseForm result = new ResponseForm();
        Map<String, Object> paramMap = (Map<String, Object>) param.getData();
        try {
            List<Coupon> couponList = couponMapper.getReceiveList(paramMap);
            result.setData(couponList);
        } catch (Exception e) {
            result.setStatus(false);
            result.setMessage(LogInfo.ERROR);
            log.error("查询领取优惠券列表error", e);
        }
        return result;
    }

    @Override
    public ResponseForm myCouponList(RequestForm param) {
        ResponseForm result = new ResponseForm();
        Map<String, Object> paramMap = (Map<String, Object>) param.getData();
        try {
            String wxUid = (String) paramMap.get("wxUid");
            String filter = (String) paramMap.get("filter");
            if (!StringUtils.isNotBlank(wxUid) || !StringUtils.isNotBlank(filter)) {
                result.setStatus(false);
                result.setMessage(LogInfo.PARAM_ERROR);
                log.error(LogInfo.PARAM_ERROR);
                return result;
            }
            List<Coupon> couponList;
            switch (filter) {
                case "1":
                    couponList = couponMapper.getMyCouponListUnused(paramMap);
                    break;
                case "2":
                    couponList = couponMapper.getMyCouponListUsed(paramMap);
                    break;
                case "3":
                    couponList = couponMapper.getMyCouponListExpired(paramMap);
                    break;
                default:
                    couponList = couponMapper.getMyCouponListUnused(paramMap);
                    break;
            }
            result.setData(couponList);
        } catch (Exception e) {
            result.setStatus(false);
            result.setMessage(LogInfo.ERROR);
            log.error("查询我的优惠券列表error", e);
        }
        return result;
    }

    @Override
    public ResponseForm getCouponById(RequestForm param) {
        ResponseForm result = new ResponseForm();
        if (param.getData() != null) {
            Map<String, Object> paramMap = (Map<String, Object>) param.getData();
            Integer id = (Integer) paramMap.get("id");
            String inviteCode = (String) paramMap.get("inviteCode");
            Map resultMap = new HashMap<>();
            try {
                Map coupon = couponMapper.getCouponById(id);
                List activityInfos = couponMapper.getActivityInfoByCouponId(id);
                coupon.put("activityInfos", activityInfos);
                resultMap.put("coupon", coupon);
                WxUser promoter = new WxUser();
                if (StringUtils.isNotBlank(inviteCode)) {
                    promoter.setVerifyPhone(inviteCode);
                    promoter = wuMapper.selectOne(promoter);
                    resultMap.put("promoter", promoter);
                }
                result.setData(resultMap);
                result.setCode("200");
                result.setStatus(true);
            } catch (Exception e) {
                result.setStatus(false);
                result.setCode("500");
                result.setMessage(LogInfo.ERROR);
                log.error("查询优惠券信息ERROR", e);
            }
        }
        return result;
    }

    @Override
    public ResponseForm orderCouponList(RequestForm param) {
        ResponseForm result = new ResponseForm();
        Map<String, Object> paramMap = (Map<String, Object>) param.getData();
        try {
            String orderId = (String) paramMap.get("orderId");
            if (!StringUtils.isNotBlank(orderId)) {
                result.setStatus(false);
                result.setMessage(LogInfo.PARAM_ERROR);
                log.error(LogInfo.PARAM_ERROR);
                return result;
            }
            Map<String, Object> orderMap = orderMapper.getOrderByIdAndStoreNo(orderId, null);
            List<Coupon> couponList = couponMapper.getOrderCouponList(orderMap);
            result.setData(couponList);
        } catch (Exception e) {
            result.setStatus(false);
            result.setMessage(LogInfo.ERROR);
            log.error("查询订单页优惠券列表error", e);
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseForm orderCouponUse(RequestForm param) {
        ResponseForm result = new ResponseForm();
        Map<String, Object> paramMap = (Map<String, Object>) param.getData();
        try {
            String wxUid = (String) paramMap.get("wxUid");
            String orderId = (String) paramMap.get("orderId");
            String action = (String) paramMap.get("action");
            String lastCouponId = (String) paramMap.get("lastCouponId");
            String couponId = (String) paramMap.get("couponId");
            Integer couponAmount = (Integer) paramMap.get("couponAmount");
            Integer lastCouponAmount = (Integer) paramMap.get("lastCouponAmount");
            if (!StringUtils.isNotBlank(wxUid) || !StringUtils.isNotBlank(orderId)) {
                result.setStatus(false);
                result.setMessage(LogInfo.PARAM_ERROR);
                log.error(LogInfo.PARAM_ERROR);
                return result;
            }

            switch (action) {
                // 使用优惠券
                case "1":
                    if ("".equals(lastCouponId) || lastCouponId == null) {
                        // 第一次使用优惠券
                        couponMapper.useCoupon(paramMap);

//                        //修改订单对应流水价格
//                        HashMap<String, Object> hashMap = new HashMap<>();
//                        hashMap.put("orderId", orderId);
//                        hashMap.put("couponAmount", couponAmount);
//                        payMapper.modifyPayOrderCouponPrice(hashMap);

                    } else {
                        // 切换优惠券
                        couponMapper.notUseCoupon(paramMap);
                        couponMapper.useCoupon(paramMap);

//                        //修改订单对应流水价格
//                        HashMap<String, Object> hashMap = new HashMap<>();
//                        hashMap.put("orderId", orderId);
//                        hashMap.put("couponAmount", lastCouponAmount - couponAmount);
//                        payMapper.modifyPayOrderCouponPrice(hashMap);
                    }
                    break;
                // 不使用优惠券
                case "2":
                    couponMapper.notUseCoupon(paramMap);

//                    //修改订单对应流水价格
//                    HashMap<String, Object> hashMap = new HashMap<>();
//                    hashMap.put("orderId", orderId);
//                    hashMap.put("couponAmount", 0 - lastCouponAmount);
//                    payMapper.modifyPayOrderCouponPrice(hashMap);
                    break;
            }

        } catch (Exception e) {
            result.setStatus(false);
            result.setMessage(LogInfo.ERROR);
            log.error("使用优惠券error", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    @Override
    public void bindNewUserCoupons(String wxUid) {
        log.debug("绑定新人优惠券,wxUid=" + wxUid);
        try {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("wxUid", wxUid);
            //用户已领取优惠券
            List<Integer> receivedCouponIdList = couponMapper.getReceivedIdListV2(hashMap);
            //所有新人优惠券
            List<Coupon> newUserCoupons = couponMapper.getNewUserCoupons();
            ArrayList<Integer> newUserCouponIdList = new ArrayList<>();
            for (Coupon newUserCoupon : newUserCoupons) {
                newUserCouponIdList.add(newUserCoupon.getId());
            }
            newUserCouponIdList.removeAll(receivedCouponIdList);
            //绑定新人优惠券
            if (newUserCouponIdList.size() > 0) {
                List<Map<String, Object>> receivableIdList = new ArrayList<>();
                for (Integer newUserCouponId : newUserCouponIdList) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("wxUid", wxUid);
                    map.put("couponId", newUserCouponId);
                    receivableIdList.add(map);
                }
                couponMapper.createCouponUser(receivableIdList);
            }
        } catch (Exception e) {
            log.error("绑定新人优惠券error,wxUid=" + wxUid, e);
        }
    }

    /**
     * 给老用户绑定新人优惠券
     *
     * @param couponId
     */
    private void bindNewUserCouponsToOldUsers(Integer couponId) {
        List<WxUser> wxUsers = wuMapper.selectAll();
        List<Map<String, Object>> receivableIdList = new ArrayList<>();
        for (WxUser wxUser : wxUsers) {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("wxUid", wxUser.getWxUid());
            hashMap.put("couponId", couponId);
            receivableIdList.add(hashMap);
        }
        //可领取的优惠券入库
        couponMapper.createCouponUser(receivableIdList);
    }

}
